//路由文件 ，四个步骤
//1.加载express
//2.创建路由对象
//3.把接口挂载到路由对象上
//4.导出路由对象
const path=require('path');
const db=require(path.join(__dirname,'../utils/db.js'));
const express=require('express');
const router=express.Router();
const utility=require('utility');
const jsonwebtoken=require('jsonwebtoken');

//--------------这里写接口------
//---------注册的接口----------
router.post('/reguser',async (req,res)=>{
	console.log(req.body);
	req.body.password=utility.md5(req.body.password);
	let r=await db('insert into user set ?',req.body);
	console.log(r);
	if(r && r.affectedRows>0){
		//成功
		res.send({
			status:0,
			message:'注册成功'
		});
			
	}else{
		res.send({
			status:1,
			message:'注册失败'
		})
	}
});
//---------登录的接口----------
router.post('/login',async (req,res)=>{
	//通过req.body接收username和password
	let username=req.body.username;
	let password=utility.md5(req.body.password);
	let r=await db('select * from user where username=? and password=?',[username,password]);
	//console.log(req.body.username,req.body.password);
	console.log(r);//返回数组
	if(r && r.length>0){
		res.send({
				status:0,
				message:'登录成功',
				//Bearer后面有空格
				//token:jsonwebtoken.sign('数据','用户加密的字符串'，’配置项‘)
				token:'Bearer ' +jsonwebtoken.sign(
				{username:req.body.username,id:r[0].id},'bigevent',{expiresIn:'2 days'}),
			})
	}else{
		res.send({
			status:1,message:'等录失败'
		})
	}
});
//gitee.com/laotang1234/bigEvent/issues
module.exports=router;